<?php

namespace app\controller;

use app\BaseController;
use app\model\City;
use app\utils\CharacterUtils;
use app\validate\CityValidate;
use think\exception\ValidateException;

class CityController extends BaseController
{
    public function getList(){
        $keyword = $this->request->param('keyword', '');

        $cityDao = new City();

        return $this->returnJson($cityDao->where('city|city_name|province','like', '%'.$keyword.'%')->select());
    }

    public function add(){
        $param = $this->request->param();
        $cityDao = new City();


        $inList = [];
        $errorList = [];
        $successList = [];
        foreach ($param as $item){
            try {
                validate(CityValidate::class)
                    ->scene('add')
                    ->check($item);
            }catch (ValidateException $validateException){
                $errorList[] = $item;
                continue;
            }

            $city = $cityDao->where('city', $item['city'])->find();
            if (!empty($city)) {
                $city['now_city'] = $item['city'];
                $city['now_city_name'] = $item['city_name'];
                $city['now_province'] = $item['province'];
                $inList[] = $city;
                continue;
            }
            $successList[] = $cityDao->create($item);

        }

        return $this->returnJson(['in'=>$inList,'error'=>$errorList,'success'=>$successList]);
    }

    public function batchUpdate(){
        $param = $this->request->param();
        $cityDao = new City();
        $errorList = [];
        $successList = [];
        foreach ($param as $item){
            try {
                validate(CityValidate::class)
                    ->scene('update')
                    ->check($item);
            }catch (ValidateException $validateException){
                $errorList[] = $item;
                continue;
            }

            $successList[] = $cityDao->update($item);


        }


        return $this->returnJson(['error'=>$errorList,'success'=>$successList]);
    }


    public function getById(City $city){

        return $this->returnJson($city['city']);
    }
}